const cloud = require("wx-server-sdk")
const TcbRouter = require('tcb-router')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
  
})
exports.main = async (event, context) => {
  const app = new TcbRouter ({event})

  app.use( async(ctx,next)=>{
    ctx.data = {},
    await next()
  })
  app.router('ImgCheck', async (ctx, next) => {
    let ImgBuffer = event.ImgBuffer
    console.log('img',ImgBuffer)
    try {
      const res = await cloud.openapi.security.imgSecCheck({
        media: {
        header: {
        "Content-Type": "application/octet-stream"},
        contentType: "image/png",
        value: Buffer.from(ImgBuffer)
      }
    })
    console.log('res',res)
    ctx.data = res;
    ctx.body = { code: 0, data: ctx.data };
    
  } catch (err) {
    ctx.data = {errCode:'87014'};
    ctx.body = { code: 0, data: ctx.data};
    console.log('err',err)
  }
  await next();  
});

  app.router('MsgCheck', async(ctx,next) => {
    let msg = event.msg
    console.log('msg',msg)
    try {
      const res = await cloud.openapi.security.msgSecCheck({
        content:msg
      })
      console.log('res',res)
      ctx.data = res;
      ctx.body = { code: 0, data: ctx.data};
      
    } catch (error) {
      ctx.data = {errCode:'87014'};
      ctx.body = { code: 0, data: ctx.data};
      console.log('error',error)
    }
    await next(); 
  })
  
return app.serve();
}